package org.sixtynine.stock.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.sixtynine.stock.Constants.CommonData;
import org.sixtynine.stock.ReturnData;
import org.sixtynine.stock.dto.GridPramDTO;
import org.sixtynine.stock.dto.Page;
import org.sixtynine.stock.entity.BaseEntity;
import org.sixtynine.stock.entity.Sector;
import org.sixtynine.stock.entity.User;
import org.sixtynine.stock.model.FileUploadForm;
import org.sixtynine.stock.model.LoadingSearchCriteria;
import org.sixtynine.stock.service.GenericService;
import org.sixtynine.stock.service.SectorService;
import org.sixtynine.stock.service.content.DataManagerService;
import org.sixtynine.stock.service.file.ExcelProcessorFactory;
import org.sixtynine.stock.service.file.FileDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Thilan
 * 
 *         this class use to add , edit and delete sector data
 * 
 */

@Controller
@SessionAttributes
public class SectorController extends BackEndAuthController {

	/** TODO configure */
	private int RECORDS_PER_PAGE = 10;

	@Autowired
	private GenericService genericService;

	@Autowired
	private FileDataService fileDataService;

	@Autowired
	DataManagerService dataManagerService;

	@Autowired
	SectorService sectorService;

	@RequestMapping(value = "/admin/sector/search")
	public ModelAndView search(@ModelAttribute LoadingSearchCriteria criteria) {
		ModelAndView modelAndView = new ModelAndView("/admin/sector/list");
		loadData(1, -1, criteria.getName(), modelAndView, criteria);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/sector/add")
	public ModelAndView addSector(HttpServletRequest request) {
		ModelAndView modelAndView = null;

		if (!isUserLogged(request)) {
			modelAndView = new ModelAndView("/login/login");
			modelAndView.addObject("registedUser", new User());
			return modelAndView;
		}
		modelAndView = new ModelAndView("/admin/sector/add");
		modelAndView.addObject("sector", new Sector());
		modelAndView.addObject("userLogged", true);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/sector/add/file_process")
	public ModelAndView addingCompaniesByFile(
			@ModelAttribute("uploadFile") FileUploadForm uploadFile) {

		ModelAndView modelAndView = new ModelAndView("/admin/sector/list");

		List<BaseEntity> sectors = genericService.findAll(Sector.class);
		modelAndView.addObject("sectors", sectors);

		MultipartFile multipartFile = uploadFile.getFile();
		ReturnData<String> fileSaveReturnData = fileDataService.saveFile(
				multipartFile, ExcelProcessorFactory.FILE_TYPE_SECTOR_LIST,
				null);

		StringBuilder message = new StringBuilder();
		if (fileSaveReturnData._isSuccess()) {
			// if success, process it
			ReturnData<List<? extends BaseEntity>> returnData = fileDataService
					.process(multipartFile.getOriginalFilename(),
							ExcelProcessorFactory.FILE_TYPE_SECTOR_LIST);
			if (returnData._isSuccess()) {
				message.append("file " + multipartFile.getOriginalFilename()
						+ " uploaded and inserted successfully");
				modelAndView = new ModelAndView("/admin/sector/list");

				loadData(1, -1, null, modelAndView, null);

				// update the cache
				dataManagerService.loadData(CommonData.SECTOR.toString(),
						Sector.class);

			} else {
				message.append(returnData.getMsg());
			}
		} else {
			message.append(fileSaveReturnData.getMsg());
		}
		modelAndView.addObject("message", message);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/sector/add/process")
	public ModelAndView addingSector(@ModelAttribute @Valid Sector sector,
			BindingResult result) {

		ModelAndView modelAndView = null;
		if (!result.hasErrors()) {
			genericService.saveOrUpdate(sector);

			modelAndView = new ModelAndView("/admin/sector/list");
			loadData(1, -1, null, modelAndView, null);
			modelAndView.addObject("userLogged", true);
		} else {
			modelAndView = new ModelAndView("/admin/sector/add");
			modelAndView.addObject("sector", new Sector());
			modelAndView.addObject("userLogged", true);
		}
		return modelAndView;

	}

	@RequestMapping(value = "/admin/sector/list")
	public ModelAndView listOfSectors(
			HttpServletRequest request,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "totalRecords", required = false) Integer totalRecords) {

		ModelAndView modelAndView = null;

		if (!isUserLogged(request)) {
			modelAndView = new ModelAndView("/login/login");
			modelAndView.addObject("registedUser", new User());
			return modelAndView;
		}
		modelAndView = new ModelAndView("/admin/sector/list");
		loadData(page, totalRecords, null, modelAndView, null);
		modelAndView.addObject("userLogged", true);

		return modelAndView;
	}

	/**
	 * load data
	 * 
	 * @param page
	 * @param totalRecords
	 * @param companyId
	 * @param fromDate
	 * @param toDate
	 * @param modelAndView
	 */
	private void loadData(Integer page, Integer totalRecords, String name,
			ModelAndView modelAndView, LoadingSearchCriteria criteria) {
		GridPramDTO gridPramDTO = new GridPramDTO();
		gridPramDTO.setRows(RECORDS_PER_PAGE);
		if (page != null) {
			gridPramDTO.setPage(page);
		} else {
			gridPramDTO.setPage(1);
		}
		if (totalRecords != null) {
			gridPramDTO._setTotalNumberOfRecords(totalRecords);
		}

		Page<Sector> sectorPage = sectorService.searchSector(name, gridPramDTO);
		modelAndView.addObject("sectorPage", sectorPage);

		if (criteria == null) {
			criteria = new LoadingSearchCriteria();

			criteria.setName(name);

		}
		modelAndView.addObject("criteria", criteria);

	}

	@RequestMapping(value = "/admin/sector/edit/{id}", method = RequestMethod.GET)
	public ModelAndView editSector(HttpServletRequest request,
			@PathVariable Integer id) {
		ModelAndView modelAndView = null;

		if (!isUserLogged(request)) {
			modelAndView = new ModelAndView("/login/login");
			modelAndView.addObject("registedUser", new User());
			return modelAndView;
		}
		modelAndView = new ModelAndView("/admin/sector/edit");
		BaseEntity sector = genericService.findById(id, Sector.class);
		modelAndView.addObject("sector", sector);
		modelAndView.addObject("userLogged", true);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/sector/edit/{id}", method = RequestMethod.POST)
	public ModelAndView edditingSector(@ModelAttribute @Valid Sector sector,
			BindingResult result, @PathVariable Integer id) {

		if (!result.hasErrors()) {
			genericService.saveOrUpdate(sector);

			ModelAndView modelAndView = new ModelAndView("/admin/sector/list");

			List<BaseEntity> sectors = genericService.findAll(Sector.class);
			modelAndView.addObject("sectors", sectors);

			loadData(1, -1, sector.getName(), modelAndView, null);

			String message = "Sector was successfully edited.";
			modelAndView.addObject("message", message);

			return modelAndView;
		} else {
			ModelAndView modelAndView = new ModelAndView("/admin/sector/edit");
			return modelAndView;
		}
	}

	@RequestMapping(value = "/admin/sector/delete/{id}", method = RequestMethod.GET)
	public ModelAndView deleteSector(@PathVariable Integer id) {
		genericService.delete(id, Sector.class);

		ModelAndView modelAndView = new ModelAndView("/admin/sector/list");

		loadData(1, -1, null, modelAndView, null);

		String message = "Sector was successfully deleted.";
		modelAndView.addObject("message", message);
		return modelAndView;
	}
}
